/**
 * @sort 1
 * @name 经销商数据
 * 接口描述信息，支持html标签
 */
const { api, resp } = require("apite")
const { DB } = require("../config")
const { token } = require("../localData")
const {
	acceptProducts,
	addAccept,
	productAddNumber
} = require("../service/product")

/**
 * @name 经销商登录
 * @param {string} login 用户名：dealer-one、dealer
 * @param {string} password 密码，123456
 */
api.post("/api/user/login", async (ctx) => {
	const { login, password } = ctx.post
	if (!login) return resp.fail("用户不存在")
	if (!password) return resp.fail("密码不能为空")

	try {
		const [rows] = await DB.execute(
			"SELECT * FROM `dealers` WHERE name=? AND password=?",
			[login, password]
		)

		if (rows.length === 0) {
			ctx.body = resp.fail("账号或密码错误")
			return
		}

		const result = {
			accessToken: token,
			expiresAt: new Date(Date.now() + 1000 * 60 * 30).getTime(),
			userInfo: rows[0]
		}

		ctx.body = resp.ok(result)
	} catch (error) {
		console.error(error.message)
		ctx.body = resp.fail("账号或密码错误")
	}
})

/**
 * @name 代理的产品
 * @param {string} id 经销商的唯一值
 * @param {number} pageSize 每页大小
 * @param {number} pageNum 第几页，默认从一开始
 */
api.get("/api/dealer/accept", async (ctx) => {
	const { id, pageNum, pageSize } = ctx.query

	if (!id) {
		ctx.body = resp.fail("请传递经销商ID属性")
		return
	}
	const numb = pageNum > 0 ? Number(pageNum) : 1
	const size = pageSize > 0 ? Number(pageSize) : 5

	const offset = (numb - 1) * size

	try {
		const typeSql =
			"SELECT " +
			" prod.*," +
			" pclass.NAME AS typeName," +
			" SUM(op.productNum) AS shopNumb" +
			" FROM" +
			" `products` AS prod" +
			" INNER JOIN `product_class` AS pclass ON prod.type = pclass.id" +
			" INNER JOIN `orders_products` AS op ON op.productId = prod.id" +
			" GROUP BY" +
			" prod.id"

		let sql =
			"SELECT " +
			" dealp.dealerId," +
			" dealp.productNum," +
			" pd.*" +
			" FROM" +
			" `dealer_products` AS dealp" +
			" INNER JOIN ( " +
			typeSql +
			") AS pd ON pd.id = dealp.productId "

		const args = []

		if (id && id !== "0") {
			const filter = " HAVING dealp.dealerId = ?"
			sql += filter
			args.push(id)
		}

		sql += ` LIMIT ${size} OFFSET ${offset} `

		const [rows] = await DB.execute(sql, args)

		const [tArr] = await DB.execute(
			"SELECT COUNT(*) AS numb FROM `dealer_products` WHERE dealerId = ?",
			[id]
		)

		const total = tArr[0].numb

		ctx.body = resp.list(rows, total, { pageNum: numb, pageSize: size })
	} catch (error) {
		ctx.body = resp.fail("error")
	}
})

/**
 * @name 编辑代理产品
 * @param {string} id 经销商的唯一值
 * @param {Array} list 变更的值
 */
api.post("/api/lealer/productAdd", async (ctx) => {
	const { id, list } = ctx.post

	if (!id && id === "0") {
		ctx.body = resp.fail("经销商ID不能为空")
		return
	}

	try {
		if (list && list.length > 0) {
			const accepts = await acceptProducts(id)

			const obj = {
				add: 0,
				edit: 0
			}

			for (let i = 0; i < list.length; i++) {
				const item = list[i]

				// 存在就只修改数量
				if (accepts.includes(item.productId)) {
					productAddNumber(item.dealerId, item.productId, item.productNum)
					obj.edit++
				} else {
					// 不存在就新增
					addAccept(item.dealerId, item.productId, item.productNum)
					obj.add++
				}
			}

			ctx.body = resp.ok(obj)
		} else {
			ctx.body = resp.fail("数据列表为空")
		}
	} catch (error) {
		ctx.body = resp.fail(error)
	}
})
